import { defineStore } from 'pinia';
import {getUserInfo} from '~/api/account'
import { message } from 'ant-design-vue';

export const useUser = defineStore('user', () => {
    const isLogin = ref(false);
    const token = ref('')
    const personalInfo = ref({
        id: null,
        username: '',
        head_img: '',
        phone: '',
        pwd: '',
        position: null,
        slogan: '',
        sex: '1',
        city: null,
        learn_time: null,
        openid: null,
    });
    // 切换登录状态
    const switchLoginState = async(_token)=> {
        token.value = _token;
        await asyncuserinfo();  
    }
    // 获取用户信息
    const asyncuserinfo = async()=> {
        if(token.value) {
            isLogin.value = true;
        } else {
            isLogin.value = false;
        }
        const userInfo = await getUserInfo()
        if (userInfo.code === 0) {
            isLogin.value = true;
            personalInfo.value = { ...userInfo.data };
        }
    }
    // 退出登录
    const logout = () => {
        clearInfo();
        navigateTo('/');
        message.success('退出登录成功！');
      };
      /**
       * 清空用户信息
       */
      const clearInfo = function () {
        token.value = '';
        isLogin.value = false;
        personalInfo.value = {} as any;
        // nextTick(() => navigateTo('/'))
      };
    return {
        isLogin,
        token,
        switchLoginState,
        logout,
        personalInfo,
        asyncuserinfo
    };
}, { persist: true }
);
